from flask import request
from flask_restx import Namespace, Resource
from models.hierarchy import Hierarchy
from extensions import db
from utils.auth import token_required
import uuid

api = Namespace('hierarchies', description='层级相关操作')

@api.route('/')
class HierarchyList(Resource):
    @token_required
    def get(self):
        """获取所有层级列表"""
        hierarchies = Hierarchy.query.all()
        return {
            'status': 'success',
            'data': [hierarchy.to_dict() for hierarchy in hierarchies]
        }, 200

    @token_required
    def post(self):
        """创建新层级"""
        data = request.get_json()
        
        # 检查必填字段
        required_fields = ['name', 'level', 'parent_id']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        
        # 创建新层级
        new_hierarchy = Hierarchy(
            hierarchy_id=str(uuid.uuid4()),
            name=data['name'],
            level=data['level'],
            parent_id=data['parent_id'],
            description=data.get('description')
        )
        
        db.session.add(new_hierarchy)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '层级创建成功',
            'data': new_hierarchy.to_dict()
        }, 201

@api.route('/<hierarchy_id>')
class HierarchyDetail(Resource):
    @token_required
    def get(self, hierarchy_id):
        """获取单个层级信息"""
        hierarchy = Hierarchy.query.get_or_404(hierarchy_id)
        return {
            'status': 'success',
            'data': hierarchy.to_dict()
        }, 200

    @token_required
    def put(self, hierarchy_id):
        """更新层级信息"""
        hierarchy = Hierarchy.query.get_or_404(hierarchy_id)
        data = request.get_json()
        
        # 更新层级信息
        if 'name' in data:
            hierarchy.name = data['name']
        if 'level' in data:
            hierarchy.level = data['level']
        if 'parent_id' in data:
            hierarchy.parent_id = data['parent_id']
        if 'description' in data:
            hierarchy.description = data['description']
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '层级信息更新成功',
            'data': hierarchy.to_dict()
        }, 200

    @token_required
    def delete(self, hierarchy_id):
        """删除层级"""
        hierarchy = Hierarchy.query.get_or_404(hierarchy_id)
        
        db.session.delete(hierarchy)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '层级删除成功'
        }, 200